from django import forms
from app01 import models
from django.core.validators import RegexValidator, EmailValidator, ValidationError


class BaseForm(forms.ModelForm):  # 基类,继承ModelForm
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for key, value in self.fields.items():
            # print(key)
            value.widget.attrs['class'] = 'form-control form-select-sm ps-2'
            value.widget.attrs['autocomplete'] = 'off'  # 不显示历史输过记录
            value.widget.attrs['id'] = key + '_id'  # 加入id识别

            if key in ['funcName', 'funcType', 'Identifier', 'dataType', 'dataDefine', 'min', 'max', 'step',
                       'toProductFuc']:
                value.widget.attrs[
                    'style'] = 'height: 32px; border: 1px solid grey; margin-bottom: 10px; font-size: 13px; color: black;'
            elif key in ['unit']:
                value.widget.attrs[
                    'style'] = 'height: 32px; border: 1px solid grey; margin-bottom: 10px; font-size: 13px; color: black;'
            else:
                value.widget.attrs[
                    'style'] = 'height: 30px; background-color: #1e1f22; color: white; border: 1px solid grey;'

            if key == 'name':
                value.widget.attrs[
                    'onchange'] = 'changed("name_id",0)'  # 平台名称失去焦点值改变时的事件,查询此平台其他具体数据onblur是失去焦点,不管值改不改变都执行
            if key == 'iotInstanceId':
                value.widget.attrs['onchange'] = 'changed("iotInstanceId_id",2)'  # 实例名称失去焦点值改变时事件,查询此实例其他具体数据
            if key == 'product_key':
                value.widget.attrs['onchange'] = 'changed("product_key_id",4)'  # 产品名称失去焦点值改变时事件,查询此实例其他具体数据
            if key == 'device_name':
                value.widget.attrs['onchange'] = 'changed("device_name_id",6)'  # 产品名称失去焦点值改变时事件,查询此实例其他具体数据

            # if key == 'toAdmin':
            #     self.fields['toAdmin'].widget = HiddenInput()  # 将关联的用户id隐藏不显示在html上,因为初始化已经通过session赋值了
            # if key == 'toPlat':
            #     self.fields['toPlat'].widget = HiddenInput()  # 将关联的用户id隐藏不显示在html上
            # if key == 'toExample':
            #     self.fields['toExample'].widget = HiddenInput()  # 将关联的用户id隐藏不显示在html上,因为初始化已经通过session赋值了
            # if key == 'toProduct':
            #     self.fields['toProduct'].widget = HiddenInput()  # 将关联的用户id隐藏不显示在html上


# 用models验证,是有通过数据库表的,自我定义验证的
class PlatformModelForm(BaseForm):
    # toAdmin = ModelChoiceField(queryset=models.AdminCustomer.objects.filter(email='1870208989@qq.com'))
    class Meta:
        model = models.Platform
        fields = '__all__'
        # exclude = ["toAdmin"]  # 除了这个其他的都要校验
        # 可以不让labels显示name的标题提示
        # labels = {'name': False, }

    def clean_name(self):
        name = self.cleaned_data['name']
        if '阿里' not in name:
            raise ValidationError('平台名称必须包含：阿里平台')
        return name


class ExampleModelForm(BaseForm):
    # toPlat = ModelChoiceField(queryset=models.Platform.objects.all())
    # toPlat = PlatformModelForm()  # 表单嵌套

    class Meta:
        model = models.Example
        fields = '__all__'
        exclude = ["toPlat"]  # 除了这个其他的都要校验
        # 可以不让labels显示name的标题提示
        # labels = {'iotInstanceId': False, }


class ProductModelForm(BaseForm):
    # toExample = ModelChoiceField(queryset=models.Example.objects.all())
    toExample = ExampleModelForm()

    class Meta:
        model = models.Product
        fields = '__all__'
        exclude = ["toExample"]  # 除了这个其他的都要校验
        # labels = {'product_key': False, }


class FunDefineModelForm(BaseForm):
    # toProduct = ModelChoiceField(queryset=models.Product.objects.all())
    toProductFuc = ProductModelForm()

    class Meta:
        model = models.FunDefine
        fields = '__all__'
        exclude = ["toProductFuc", "value"]  # 除这两个其他的都要校验
        # labels = {'funcName': False, }


# class FunBakModelForm(BaseForm):
#     # toProduct = ModelChoiceField(queryset=models.Product.objects.all())
#     toProductFuc = ProductModelForm()
#
#     class Meta:
#         model = models.FunBak
#         fields = '__all__'
#         exclude = ["toProductFuc"]  # 除了这个其他的都要校验
#         # labels = {'funcName': False, }


class DeviceModelForm(BaseForm):
    # toProduct = ModelChoiceField(queryset=models.Product.objects.all())
    toProduct = ProductModelForm()

    class Meta:
        model = models.Device
        fields = '__all__'
        exclude = ["toProduct"]  # 除了这个其他的都要校验
        # labels = {'device_name': False, }


class DeviceDataModelForm(BaseForm):
    # toDevice = ModelChoiceField(queryset=models.Device.objects.all())
    toDevice = DeviceModelForm()

    class Meta:
        model = models.DeviceData
        fields = '__all__'

